using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Util;
using Admin.NET.Core;
using Furion.Schedule;
using Microsoft.Extensions.DependencyInjection;

namespace Admin.NET.Application.Job;

[JobDetail("job_loadhttpscerts", Description = "加载https证书", GroupName = "default", Concurrent = false)]
[PeriodSeconds(1L, TriggerId = "trigger_loadhttpscerts", Description = "加载https证书", MaxNumberOfRuns = 1L, RunOnStart = true)]
public class LoadHttpsCerts : IJob
{
	private readonly IServiceScopeFactory _scopeFactory;

	public LoadHttpsCerts(IServiceScopeFactory scopeFactory)
	{
		_scopeFactory = scopeFactory;
	}

	public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
	{
		_ = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "ssl";
		string wwwroot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
		using IServiceScope serviceScope = _scopeFactory.CreateScope();
		SqlSugarRepository<PlatformConfig> platConfig = serviceScope.ServiceProvider.GetService<SqlSugarRepository<PlatformConfig>>();
		foreach (PlatformConfig input in await platConfig.CopyNew().AsQueryable().ToListAsync())
		{
			if (string.IsNullOrEmpty(input.WebUrl) || string.IsNullOrEmpty(input.SslPwd) || string.IsNullOrEmpty(input.SslUrl))
			{
				continue;
			}
			try
			{
				Uri uri = new Uri(input.SslUrl);
				string path = uri.LocalPath;
				string text = path;
				path = text.Substring(1, text.Length - 1);
				string sslPath = Path.Combine(wwwroot, path);
				if (File.Exists(sslPath))
				{
					byte[] bytearry = File.ReadAllBytes(sslPath);
					UtilCertDic.SetCertDic(x509Certificate2: new X509Certificate2(bytearry, input.SslPwd), key: input.WebUrl);
					Console.WriteLine(input.SslUrl + "证书加载成功，" + sslPath);
				}
				else
				{
					Console.WriteLine(input.SslUrl + "证书找不到，" + sslPath);
				}
			}
			catch (Exception ex2)
			{
				Exception ex = ex2;
				Console.WriteLine($"{input.SslUrl}证书加载失败，{ex.Message} {ex.StackTrace}");
			}
		}
	}
}
